package com.ooqiu.gaming.ui.person.edit_profile;

import android.app.Activity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

import com.airsaid.pickerviewlibrary.TimePickerView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.miguelbcr.ui.rx_paparazzo2.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo2.entities.FileData;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.SmallSize;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.FileManager;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.base.BaseActivity;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.common.entities.GamingUser;
import com.ooqiu.gaming.components.glide.GlideApp;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.dialog.ChoiceDialog;
import com.ooqiu.gaming.ui.dialog.SimpleEditDialog;
import com.ooqiu.gaming.ui.feedback.UploadRes;
import com.ooqiu.gaming.view.Topbar;
import com.ooqiu.gaming.view.option_item.OptionItem;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

@Route(path = EditProfileActivity.PATH, extras = Constants.ROUTER_EXTRA_NEED_LOGIN)
public class EditProfileActivity extends BaseActivity {
    public static final String PATH = "/user/edit_profile";
    @BindView(R.id.topbar)
    Topbar mTopbar;
    @BindView(R.id.img_header)
    CircleImageView mImgHeader;
    @BindView(R.id.option_header)
    OptionItem mOptionHeader;
    @BindView(R.id.option_nickname)
    OptionItem mOptionNickname;
    @BindView(R.id.option_birth)
    OptionItem mOptionBirth;
    @BindView(R.id.option_sex)
    OptionItem mOptionSex;
    @BindView(R.id.option_apply)
    Switch mOptionApply;
    @BindView(R.id.btn_logout)
    Button mBtnLogout;
    UserStorage mUserStorage;
    GamingApi mGamingApi;


    FileManager mFileManager;
    @BindView(R.id.option_username)
    OptionItem mOptionUsername;


    @Override
    public int initContentView() {
        return R.layout.activity_edit_profile;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        mUserStorage = getApplicationComponent().getUserStorage();
        mGamingApi = getApplicationComponent().getGamingApi();
        mFileManager = getApplicationComponent().getFileManager();

    }

    @Override
    public void initUiAndListener() {


        updateProfile(mUserStorage.getUser());
        mOptionHeader.setOnItemClickListener(new OptionItem.OnItemClickListener() {
            @Override
            public void onItemClick(OptionItem item) {
                choiceHeader();
            }
        });


        mOptionSex.setOnItemClickListener(new OptionItem.OnItemClickListener() {
            @Override
            public void onItemClick(OptionItem item) {
                choiceSex();
            }
        });


        mOptionBirth.setOnItemClickListener(new OptionItem.OnItemClickListener() {
            @Override
            public void onItemClick(OptionItem item) {
                choiceDate();
            }
        });

        mOptionNickname.setOnItemClickListener(new OptionItem.OnItemClickListener() {
            @Override
            public void onItemClick(OptionItem item) {
                SimpleEditDialog.newInstance().setTitle("输入昵称")
                        .setListener(new SimpleEditDialog.OnClickListener() {
                            @Override
                            public void onEnter(String content) {
                                editProfile("name", content, 0);
                            }
                        }).show(getSupportFragmentManager());
            }
        });


        mOptionApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editProfile("anonymous", String.valueOf(mOptionApply.isChecked() ? 1 : 2), 1);
            }
        });

        mOptionBirth.getSubView().setHintTextColor(getResources().getColor(R.color.colorAccent));
        mOptionBirth.getSubView().setHint("点击添加生日");


        mOptionUsername.setSubText(mUserStorage.getUser().getUsername());

    }

    private void choiceSex() {
        final List<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        ChoiceDialog.newInstance()
                .setTitle("选择性别")
                .setDatas(sexList)
                .setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        editProfile("sex", sexList.get(position), 2);
                    }
                })
                .show(getSupportFragmentManager());
    }


    private void updateProfile(GamingUser user) {
        GlideApp.with(this).load(user.getFace()).into(mImgHeader);
        mOptionNickname.setSubText(user.getName());
        mOptionBirth.setSubText(user.getBirth());
        mOptionSex.setSubText(user.getSex());
        mOptionApply.setChecked(user.getAnonymous() == 1);
    }

    private void choiceHeader() {
        List<String> m = new ArrayList<>();
        m.add("拍照");
        m.add("相册");
        ChoiceDialog.newInstance()
                .setTitle("上传头像")
                .setDatas(m)
                .setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        switch (position) {
                            case 0:
                                RxPaparazzo.single(EditProfileActivity.this)
                                        .useInternalStorage()
                                        .size(new SmallSize())
                                        .usingCamera()
                                        .subscribeOn(Schedulers.io())
                                        .flatMap(new Function<Response<EditProfileActivity, FileData>, ObservableSource<UploadRes>>() {
                                            @Override
                                            public ObservableSource<UploadRes> apply(Response<EditProfileActivity, FileData> fileData) throws Exception {
                                                if (fileData.resultCode() == Activity.RESULT_OK) {
                                                    return mFileManager.uploadImg(fileData.data().getFile().getAbsolutePath())
                                                            .subscribeOn(Schedulers.io());
                                                } else {
                                                    throw new IllegalStateException("取消上传");

                                                }
                                            }
                                        })
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext(new Consumer<UploadRes>() {
                                            @Override
                                            public void accept(UploadRes uploadRes) throws Exception {
                                                editProfile("face", uploadRes.getName(), 3);
                                            }
                                        })

                                        .subscribe(new DefaultObserver<UploadRes>() {
                                            @Override
                                            public void onNext(UploadRes uploadRes) {

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                Toast.makeText(EditProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });


                                break;
                            case 1:
                                RxPaparazzo.single(EditProfileActivity.this)
                                        .useInternalStorage()
                                        .size(new ScreenSize())
                                        .usingGallery()
                                        .subscribeOn(Schedulers.io())
                                        .flatMap(new Function<Response<EditProfileActivity, FileData>, ObservableSource<UploadRes>>() {
                                            @Override
                                            public ObservableSource<UploadRes> apply(Response<EditProfileActivity, FileData> fileData) throws Exception {
                                                if (fileData.resultCode() == Activity.RESULT_OK) {
                                                    return mFileManager.uploadImg(fileData.data().getFile().getAbsolutePath())
                                                            .subscribeOn(Schedulers.io());
                                                } else {
                                                    throw new IllegalStateException("取消上传");
                                                }
                                            }
                                        })
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext(new Consumer<UploadRes>() {
                                            @Override
                                            public void accept(UploadRes uploadRes) throws Exception {
                                                editProfile("face", uploadRes.getName(), 3);
                                            }
                                        })
                                        .subscribe(new DefaultObserver<UploadRes>() {
                                            @Override
                                            public void onNext(UploadRes uploadRes) {

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });


                                break;
                        }

                    }

                })
                .show(getSupportFragmentManager());
    }


    private void choiceDate() {
        //     TimePickerView 同样有上面设置样式的方法
        TimePickerView mTimePickerView = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        // 设置是否循环
//        mTimePickerView.setCyclic(true);
        // 设置滚轮文字大小
//        mTimePickerView.setTextSize(TimePickerView.TextSize.SMALL);
        // 设置时间可选范围(结合 setTime 方法使用,必须在)
//        Calendar calendar = Calendar.getInstance();
//        mTimePickerView.setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR));
        // 设置选中时间
//        mTimePickerView.setTime(new Date());
        mTimePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {

                editProfile("birth", new SimpleDateFormat("yyyy-MM-dd").format(date), 4);

//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
//                Toast.makeText(mContext, format.format(date), Toast.LENGTH_SHORT).show();
            }
        });
        mTimePickerView.show();

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return mTopbar;
    }

    @Override
    protected View statusLayoutId() {
        return null;
    }

    @OnClick(R.id.btn_logout)
    public void logout() {
        QMUIDialog.MessageDialogBuilder builder = new QMUIDialog.MessageDialogBuilder(mContext);
        builder.setTitle("提示：");
        builder.setMessage("确定退出该账号吗？");

        builder
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })

                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        mUserStorage.logout(true);
                        dialog.dismiss();
                        finish();
                    }
                });

        builder.create().show();


    }


    private void editProfile(String filed, String value, final int type) {
        mGamingApi.editProfile(filed, value)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<GamingUser>(mContext) {
                    @Override
                    public void onNext(GamingUser user) {

                        switch (type) {
                            case 0:
                                mUserStorage.getUser().setName(user.getName());
                                break;
                            case 1:

                                break;
                            case 2:
                                mUserStorage.getUser().setSex(user.getSex());
                                break;
                            case 3:
                                mUserStorage.getUser().setFace(user.getFace());
                                break;
                            case 4:
                                mUserStorage.getUser().setBirth(user.getBirth());
                                break;

                        }

                        mUserStorage.saveUser(mUserStorage.getUser());
                        updateProfile(mUserStorage.getUser());
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

}
